﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ProjectFitus.Models;

namespace ProjectFitus.Controllers
{
	[HandleError]
	public class NewsController : Controller
    {
		IDBFitusRepository m_repo;
	
		//default smiður fyrir db
		public NewsController()
		{
			m_repo = new DBFitusRepository();
		}

		//smiður fyrir testing
		public NewsController(IDBFitusRepository repo)
		{
			m_repo = repo;
		}

		protected override void OnException(ExceptionContext fc)
		{
			base.OnException(fc);
			FitusLogger.Instance.LogException(fc.Exception);

		}
		
        public ActionResult Index()
        {
			var allNews = m_repo.GetAllNews().Take(10);
			System.Web.HttpRuntime.Cache["MenuItemsSub"] = m_repo.GetMenuItemsByParentId(2);
			return View(allNews);
        }

		[HttpGet]
        public ActionResult Details(long id)
        {
			var news = m_repo.GetNewsById(id);
			User newsAuthor = m_repo.GetUserById(news.writtenByUserId);
			ViewData["Author"] = String.Format("{0} {1}", newsAuthor.firstName, newsAuthor.lastName);
			IEnumerable<SelectListItem> catList = m_repo.GetContentCategoryByParentId(2, 2);
			string catListString = "";
			foreach (var cl in catList)
				catListString = cl.Text + ", ";

			ViewData["CatsString"] = catList;

			if (news.NewsToCategories.Count > 0)
				ViewData["SelectedCategoryName"] = m_repo.GetCategoryNameById(news.NewsToCategories.FirstOrDefault().categoryId).categoryTitle;
			else
				ViewData["SelectedCategoryName"] = "flokkur er óskráður";
			return View(news);
        }

		[Authorize(Roles = "Administrators")]
        public ActionResult Create()
        {
			ViewData["Cats"] = m_repo.GetContentCategoryByParentId(2, 2);
            return View();
        } 

		
        [HttpPost]
		[Authorize(Roles = "Administrators")]
        public ActionResult Create(FormCollection formData)
        {
			//if (ModelState.IsValid)
			//{
			NewsContent news = new NewsContent();
			if (!String.IsNullOrEmpty(formData["title"]) && !String.IsNullOrEmpty(formData["contentText"]) 
				&& !String.IsNullOrEmpty(formData["introText"]) && !String.IsNullOrEmpty(formData["Cats"]))
 			{
				System.Web.Security.MembershipUser CurrentUser = System.Web.Security.Membership.GetUser(User.Identity.Name);
				news.writtenByUserId = m_repo.GetUserIdByAspNetUsrId((Guid)CurrentUser.ProviderUserKey);
				news.title = formData["title"];	
				news.dateCreated = DateTime.Now;
				news.contentText = formData["contentText"];
				news.introText = formData["introText"];
				news.contentText.Replace("&lt;", "<").Replace("&gt;", ">").Replace("&amp;", "&");
				news.introText.Replace("&lt;", "<").Replace("&gt;", ">").Replace("&amp;", "&");
				string test = formData["isActive"];
				if (formData["isActive"].Trim().ToLower() == "on") //microsoft! on eða off wtf
					news.isActive = true;
				int selectedCatId;
				int.TryParse(formData["Cats"], out selectedCatId);
				m_repo.AddNews(news);
				news.NewsToCategories.Add(new NewsToCategory{categoryId = selectedCatId});
				m_repo.SaveChanges();
				System.Web.HttpRuntime.Cache["Global3NewestNews"] = m_repo.GetAllNews().Take(3);
                System.Web.HttpRuntime.Cache["Global5NewestNews"] = m_repo.GetNewsByCategoryId(10).Take(5);
                System.Web.HttpRuntime.Cache["Global5NewestEvents"] = m_repo.GetNewsByCategoryId(28).Take(5);
                return RedirectToAction("Index");
			}	
				IEnumerable<SelectListItem> catList = m_repo.GetContentCategoryByParentId(2, 2);
				ViewData["Cats"] = catList;
				return View(news);
        }

		[Authorize(Roles = "Administrators")]
		public ActionResult Edit(int id)
        {
			var news = m_repo.GetNewsById(id);
			news.contentText = Server.HtmlDecode(news.contentText);
			news.introText = Server.HtmlDecode(news.introText);
			IEnumerable<SelectListItem> catList = m_repo.GetContentCategoryByParentId(2, 2);
			int selectedCatId = m_repo.GetNewsSelectedCategoryId(news.id);
			ViewData["oldCatId"] = selectedCatId.ToString();
			string strDropDownOptions = "";
			string strSelAttr = "";
			foreach (var cl in catList)
			{
				strSelAttr = (selectedCatId.ToString() == cl.Value) ? " selected=\"selected\"" : "";
					strDropDownOptions += "<option value=\"" + cl.Value + "\" " + strSelAttr + ">" + cl.Text + "</option>\n"; 
			}
			ViewData["Cats"] = strDropDownOptions;

			return View(news);
        }

		[HttpPost]
		[Authorize(Roles = "Administrators")]
		public ActionResult Edit(FormCollection formData)
        {
			NewsContent news = new NewsContent();
			long longId;
			if (long.TryParse(formData["newsId"], out longId))
				news.id = longId;

			if (!String.IsNullOrEmpty(formData["title"]))	
			{
				System.Web.Security.MembershipUser CurrentUser = System.Web.Security.Membership.GetUser(User.Identity.Name);
				news.lastEditedByUserId = m_repo.GetUserIdByAspNetUsrId((Guid)CurrentUser.ProviderUserKey);
				news.title = formData["title"];
				int intIsActive;
				news.isActive = int.TryParse(formData["isActive"], out intIsActive);
				news.contentText = formData["contentText"];
				news.contentText.Replace("&lt;", "<").Replace("&gt;", ">").Replace("&amp;", "&");
				news.introText = formData["introText"];
				news.introText.Replace("&lt;", "<").Replace("&gt;", ">").Replace("&amp;", "&");
				m_repo.UpdateNews(news);
				m_repo.SaveChanges();

				int oldCatId;
				int.TryParse(formData["oldCategoryId"], out oldCatId);
				int currentCatId;
				int.TryParse(formData["Cats"], out currentCatId);

				m_repo.UpdateNewsToCategories(news.id, currentCatId, oldCatId);
				m_repo.SaveChanges();
				System.Web.HttpRuntime.Cache["Global3NewestNews"] = m_repo.GetAllNews().Take(3);
				System.Web.HttpRuntime.Cache["Global5NewestEvents"] = m_repo.GetNewsByCategoryId(28).Take(5);
					return RedirectToAction("Index");
				}
			return View(news);
        }

		[Authorize(Roles = "Administrators")]
        public ActionResult Delete(int id)
        {
            return View();
        }

        [HttpPost]
		[Authorize(Roles = "Administrators")]
		public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        } 		
    }
}
